/**
 * 报表图表组合模块
 * gf
 */
import { Dropdown, Menu, Spin, Table } from "antd";
import React, { Fragment, useEffect, useState } from "react";
import styles from "../index.less";
import select_arrow from "@/assets/icons/icon-arrow.png";
import { intervalPositiveRepo, counterparty, trader } from "../service";
import cn from "classnames";
import Pie from "@/components/EchartsComponents/Pie/pie";
import { getBaseColors } from "@/utils/echarts";
import dayjs from 'dayjs';
import StackBarVer from "./Bar";
import { getUrlParam } from "@/utils/utils";
import EventEmpty from "@/components/FOF/EventEmpty";

const MENULIST = [
  {
    label: "区间正回购统计",
    value: "1",
  },
  {
    label: "区间交易对手统计",
    value: "2",
  },
  {
    label: "区间交易员统计",
    value: "3",
  },
];

const MENUMAP = {
  "1": "区间正回购统计",
  "2": "区间交易对手统计",
  "3": "区间交易员统计",
};

const isPDF = getUrlParam("type") === "img";

const TableChart = (props: {
  innerCode: string | number;
  start: string;
  end: string;
  settingBtn?: any;
  onChangeLoading: (b: boolean) => void;
  checkedkeys: string[];
}) => {
  const { innerCode, start, end, settingBtn, checkedkeys, onChangeLoading } =
    props;
  const [curMenu, setCurMenu] = useState("1");
  const [tableData, setTableData] = useState([]);
  const [columnsFilter, setColumnsFilter] = useState<any>([]);
  const [pieData, setPieData] = useState([]);
  const [barData, setBarData] = useState({});
  const [loading, setLoading] = useState(false);

  const handleQuery = (type: "1" | "2" | "3") => {
    setLoading(true);
    const params = {
      innerCode,
      start: dayjs(start).format("YYYY-MM-DD"),
      end: dayjs(end).format("YYYY-MM-DD"),
    };
    setPieData([]);
    if (type === "1") {
      onChangeLoading(false);
      intervalPositiveRepo(params).then((res) => {
        setLoading(false);
        onChangeLoading(true);
        if (res?.code === "0") {
          const pData = [];
          if (res.data.length > 0) {
            res.data.forEach((p) => {
              if (p.actualRepCode !== "合计") {
                pData.push({
                  name: p.actualRepCode,
                  value: p.moneyRatio,
                });
              }
            });
          }

          if (res.data.length < 4 && res.data.length > 0) {
            new Array(4 - res.data.length).fill("").map((v) => {
              res.data.push({});
            });
          }
          setPieData(pData);
          setTableData(res?.data || []);
        }
      });
    } else if (type === "2") {
      counterparty(params).then((res) => {
        setLoading(false);
        if (res?.code === "0") {
          const pData = [];
          if (res.data.length > 0) {
            res.data.forEach((v) => {
              pData.push({
                name: v.counterparty,
                value: v.moneyRatio,
              });
            });
          }
          if (res.data?.length < 5 && res.data?.length > 0) {
            new Array(5 - (res.data?.length || 0)).fill("").map((v) => {
              res.data.push({});
            });
          }
          setPieData(pData);
          setTableData(res.data || []);
        }
      });
    } else if (type === "3") {
      trader(params).then((res) => {
        setLoading(false);
        if (res?.code === "0") {
          if (res.data?.length < 5 && res.data?.length > 0) {
            new Array(5 - (res.data?.length || 0)).fill("").map((v) => {
              res.data.push({});
            });
          }
          setTableData(res.data || []);
          if (res?.data.length > 0) {
            const l = [];
            const x = [];
            const y = {};
            res.data.forEach((v) => {
              if (v.trader) {
                x.push(v.trader);
              }
              if (v.moneyRatioR001) {
                y["R001"]
                  ? y["R001"].push({ label: v.trader, value: v.moneyRatioR001 })
                  : (y["R001"] = [
                      { label: v.trader, value: v.moneyRatioR001 },
                    ]);
              }
              if (v.moneyRatioR014) {
                y["R007"]
                  ? y["R007"].push({ label: v.trader, value: v.moneyRatioR007 })
                  : (y["R007"] = [
                      { label: v.trader, value: v.moneyRatioR007 },
                    ]);
              }
              if (v.moneyRatioR014) {
                y["R014"]
                  ? y["R014"].push({ label: v.trader, value: v.moneyRatioR014 })
                  : (y["R014"] = [
                      { label: v.trader, value: v.moneyRatioR014 },
                    ]);
              }
              if (v.moneyRatioR021) {
                y["R021"]
                  ? y["R021"].push({ label: v.trader, value: v.moneyRatioR021 })
                  : (y["R021"] = [
                      { label: v.trader, value: v.moneyRatioR021 },
                    ]);
              }
              if (v.moneyRatioR1M) {
                y["R1M"]
                  ? y["R1M"].push({ label: v.trader, value: v.moneyRatioR1M })
                  : (y["R1M"] = [{ label: v.trader, value: v.moneyRatioR1M }]);
              }
              if (v.moneyRatioR2M) {
                y["R2M"]
                  ? y["R2M"].push({ label: v.trader, value: v.moneyRatioR2M })
                  : (y["R2M"] = [{ label: v.trader, value: v.moneyRatioR2M }]);
              }
              if (v.moneyRatioR3M) {
                y["R3M"]
                  ? y["R3M"].push({ label: v.trader, value: v.moneyRatioR3M })
                  : (y["R3M"] = [{ label: v.trader, value: v.moneyRatioR3M }]);
              }
              if (v.moneyRatioR4M) {
                y["R4M"]
                  ? y["R4M"].push({ label: v.trader, value: v.moneyRatioR4M })
                  : (y["R4M"] = [{ label: v.trader, value: v.moneyRatioR4M }]);
              }
              if (v.moneyRatioR5M) {
                y["R5M"]
                  ? y["R5M"].push({ label: v.trader, value: v.moneyRatioR5M })
                  : (y["R5M"] = [{ label: v.trader, value: v.moneyRatioR5M }]);
              }
              if (v.moneyRatioR6M) {
                y["R6M"]
                  ? y["R6M"].push({ label: v.trader, value: v.moneyRatioR6M })
                  : (y["R6M"] = [{ label: v.trader, value: v.moneyRatioR6M }]);
              }
            });
            // console.log(y, x);

            setBarData({
              legend: Object.keys(y),
              xaxis: x,
              yaxis: Object.keys(y).map((v: any) => {
                return {
                  label: v,
                  value: y[v],
                };
              }),
            });
          } else {
            setBarData({
              legend: [],
              xaxis: [],
              yaxis: [],
            });
          }
        }
      });
    }
  };

  useEffect(() => {
    if (start && end && innerCode) {
      setBarData({});
      setPieData([]);
      handleQuery(curMenu);
    }
  }, [curMenu, start, end, innerCode]);

  const columnsA = [
    {
      title: "回购类型",
      dataIndex: "actualRepCode",
      key: "actualRepCode",
    },
    {
      title: "加权利率 (%)",
      dataIndex: "rate",
      key: "rate",
      align: "right",
      render: (text, record: any) =>
        text || text === 0
          ? Number(text).toFixed(2)
          : record.actualRepCode
          ? "-"
          : "",
    },
    {
      title: "回购笔数 (笔)",
      dataIndex: "count",
      key: "count",
      align: "right",
      render: (text, record: any) =>
        text || text === 0 ? text : record.actualRepCode ? "-" : "",
    },
    {
      title: "回购金额 (亿)",
      dataIndex: "sumNetCapital",
      key: "sumNetCapital",
      align: "right",
      render: (text, record: any) =>
        text || text === 0
          ? Number(text).toFixed(2)
          : record.actualRepCode
          ? "-"
          : "",
    },
    {
      title: "金额占比 (%)",
      dataIndex: "moneyRatio",
      key: "moneyRatio",
      align: "right",
      render: (text, record: any) =>
        text || text === 0
          ? Number(text).toFixed(2)
          : record.actualRepCode
          ? "-"
          : "",
    },
  ];

  // 生成表头
  const handleGenColumnHeader = (type) => {
    const _resolveData = (text, record) =>
      text || text === 0
        ? type.indexOf("count") > -1
          ? text
          : Number(text).toFixed(2)
        : record.counterparty || record.trader
        ? "-"
        : "";

    const filterList = checkedkeys.filter((v) => v.indexOf(type) > -1);

    const arr = [
      {
        title: <div>合计</div>,
        dataIndex: type,
        key: type,
        align: "right",
        width: filterList.length > 1 ? 80 : 100,
        render: (text, record: any) => _resolveData(text, record),
      },
      {
        title: "R001",
        dataIndex: `${type}R001`,
        key: `${type}R001`,
        align: "right",
        showSorterTooltip: false,
        sorter: (a, b) => a[`${type}R001`] - b[`${type}R001`],
        width: 80,
        render: (text, record: any) => _resolveData(text, record),
      },
      {
        title: "R007",
        dataIndex: `${type}R007`,
        key: `${type}R007`,
        align: "right",
        width: 80,
        showSorterTooltip: false,
        sorter: (a, b) => a[`${type}R007`] - b[`${type}R007`],
        render: (text, record: any) => _resolveData(text, record),
      },
      {
        title: "R014",
        dataIndex: `${type}R014`,
        key: `${type}R014`,
        align: "right",
        width: 80,
        showSorterTooltip: false,
        sorter: (a, b) => a[`${type}R014`] - b[`${type}R014`],
        render: (text, record: any) => _resolveData(text, record),
      },
      {
        title: "R021",
        dataIndex: `${type}R021`,
        key: `${type}R021`,
        align: "right",
        width: 80,
        showSorterTooltip: false,
        sorter: (a, b) => a[`${type}R021`] - b[`${type}R021`],
        render: (text, record: any) => _resolveData(text, record),
      },
      {
        title: "R1M",
        dataIndex: `${type}R1M`,
        key: `${type}R1M`,
        align: "right",
        width: 80,
        showSorterTooltip: false,
        sorter: (a, b) => a[`${type}R1M`] - b[`${type}R1M`],
        render: (text, record: any) => _resolveData(text, record),
      },
      {
        title: "R2M",
        dataIndex: `${type}R2M`,
        key: `${type}R2M`,
        align: "right",
        width: 80,
        showSorterTooltip: false,
        sorter: (a, b) => a[`${type}R2M`] - b[`${type}R2M`],
        render: (text, record: any) => _resolveData(text, record),
      },
      {
        title: "R3M",
        dataIndex: `${type}R3M`,
        key: `${type}R3M`,
        align: "right",
        width: 80,
        showSorterTooltip: false,
        sorter: (a, b) => a[`${type}R3M`] - b[`${type}R3M`],
        render: (text, record: any) => _resolveData(text, record),
      },
      {
        title: "R4M",
        dataIndex: `${type}R4M`,
        key: `${type}R4M`,
        align: "right",
        width: 80,
        showSorterTooltip: false,
        sorter: (a, b) => a[`${type}R4M`] - b[`${type}R4M`],
        render: (text, record: any) => _resolveData(text, record),
      },
      {
        title: "R5M",
        dataIndex: `${type}R5M`,
        key: `${type}R5M`,
        align: "right",
        width: 80,
        showSorterTooltip: false,
        sorter: (a, b) => a[`${type}R5M`] - b[`${type}R5M`],
        render: (text, record: any) => _resolveData(text, record),
      },
      {
        title: "R6M",
        dataIndex: `${type}R6M`,
        key: `${type}R6M`,
        align: "right",
        width: 80,
        showSorterTooltip: false,
        sorter: (a, b) => a[`${type}R6M`] - b[`${type}R6M`],
        render: (text, record: any) => _resolveData(text, record),
      },
    ];
    return arr;
  };

  const columnsB = [
    {
      title: curMenu === "2" ? "交易对手名称" : "交易员",
      // dataIndex: curMenu === "2" ? "counterparty" : "trader",
      // key: "trader",
      fixed: 'left',
      children: [
        {
          title: "",
          width: 100,
          dataIndex: curMenu === "2" ? "counterparty" : "trader",
          key: curMenu === "2" ? "counterparty" : "trader",
          ellipsis: true,
          fixed: 'left'
        },
      ],
    },
    {
      title: "加权利率 (%)",
      key: "rate",
      children: handleGenColumnHeader("rate"),
    },
    {
      title: "回购笔数 (笔)",
      key: "count",
      children: handleGenColumnHeader("count"),
    },
    {
      title: "回购金额 (亿)",
      key: "sumNetCapital",
      children: handleGenColumnHeader("sumNetCapital"),
    },
    {
      title: "金额占比 (%)",
      key: "moneyRatio",
      children: handleGenColumnHeader("moneyRatio"),
    },
  ];

  // 控制表头显示
  const handleResolveColumns = (oriColumns: any) => {
    const arr = [];
    oriColumns.forEach((v) => {
      console.log(v.key);
      // if (checkedkeys.includes(v.key)) {
      //   setShowColumns((state) => {
      //     return {
      //       ...state,
      //     };
      //   });
      // }
      arr.push({
        ...v,
        children: v.children.filter(
          (m) =>
            checkedkeys.includes(m.key) ||
            m.key === "counterparty" ||
            m.key === "trader"
        ),
      });
    });
    setColumnsFilter(arr);
  };

  useEffect(() => {
    // console.log(checkedkeys);

    handleResolveColumns(columnsB);
  }, [checkedkeys, curMenu]);

  const handleChangeMenu = (e) => {
    setCurMenu(e.key);
  };

  const menu = (
    <Menu onClick={handleChangeMenu} selectedKeys={curMenu}>
      {MENULIST?.map((v) => (
        <Menu.Item key={v.value}>{v.label}</Menu.Item>
      ))}
    </Menu>
  );

  return (
    <Spin spinning={loading}>
      <div style={{ width: "100%" }}>
        <div className={styles.header}>
          <div className={styles.header_left}>
            {!isPDF ? (
              <Dropdown
                overlayClassName={styles.dropMenu}
                overlay={menu}
                trigger={["click"]}
              >
                <div>
                  <span>{MENUMAP[curMenu]}</span>
                  <img src={select_arrow} alt="下拉" />
                </div>
              </Dropdown>
            ) : (
              curMenu === "1" &&
              ((isPDF && tableData.length > 0) || !isPDF) && (
                <div className={styles.pdfMenu}>
                  <span>{MENUMAP[curMenu]}</span>
                </div>
              )
            )}
          </div>
          {isPDF || curMenu === "1" ? null : settingBtn}
        </div>
        <div
          className={cn(
            styles.tableChartBox,
            isPDF ? styles.pdfTableChart : ""
          )}
        >
          {curMenu === "1" && ((isPDF && tableData.length > 0) || !isPDF) && (
            <Fragment>
              <Table
                className={cn(
                  "list_table list_table_with_border table_header_center",
                  styles.fundReportTable,
                  isPDF ? styles.pdfTable : ""
                )}
                columns={columnsA}
                dataSource={tableData}
                pagination={false}
                style={{ whiteSpace: "nowrap" }}
                scroll={
                  isPDF
                    ? {}
                    : tableData?.length > 10
                    ? { x: "calc(100%)", y: 560 }
                    : { x: true }
                }
              />
              <div
                className={cn(
                  styles.tableChartBox_chart,
                  isPDF ? styles.pdfTableChart_chart : ""
                )}
              >
                <span>金额占比</span>
                {console.log("pieData", pieData)}
                {pieData.length > 0 ? (
                  <Pie
                    idName="actualRep-pie2"
                    pieData={pieData}
                    name="金额占比"
                    legendData={pieData?.map((v) => v.name) || []}
                    tooltipProps={{
                      formatter: `{b}: {c}%`,
                    }}
                    legendProps={{
                      orient: "horizontal",
                      top: "auto",
                      bottom: "2%",
                      width: 310,
                      padding: [
                        5, // 上
                        10, // 右
                        10, // 下
                        10, // 左
                      ],
                      itemGap: 10,
                    }}
                    pieStyle={{
                      width: "100%",
                      height: "100%",
                      radius:
                        pieData.length > 15
                          ? [55, 80]
                          : pieData.length > 10
                          ? [50, 70]
                          : [40, 60],
                    }}
                    color={[...getBaseColors()]}
                    isPdf={isPDF}
                  />
                ) : (
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      height: "100%",
                      width: "100%",
                      justifyContent: "center",
                      paddingBottom: 10,
                    }}
                  >
                    <EventEmpty title="暂无数据" />
                  </div>
                )}
              </div>
            </Fragment>
          )}
          {curMenu !== "1" && (
            <Fragment>
              <Table
                className={cn(
                  "list_table list_table_with_border table_header_center",
                  styles.fundReportTable,
                  styles.fundReportTableB
                )}
                columns={columnsFilter}
                dataSource={tableData}
                pagination={false}
                style={{ whiteSpace: "nowrap" }}
                // scroll={{x:true}}
                scroll={
                  tableData?.length > 10
                    ? { x: "calc(100%)", y: 560 }
                    : { x: true }
                }
              />
            </Fragment>
          )}
          {curMenu === "2" && (
            <div className={styles.tableChartBox_chart}>
              <span>金额占比</span>
              {pieData.length > 0 ? (
                <Pie
                  idName="actualRep-pie"
                  pieData={pieData}
                  name="金额占比"
                  legendData={pieData?.map((v) => v.name) || []}
                  tooltipProps={{
                    formatter: `{b}: {c}%`,
                  }}
                  legendProps={{
                    orient: "horizontal",
                    top: "auto",
                    bottom: "2%",
                    width: 310,
                    padding: [
                      5, // 上
                      10, // 右
                      10, // 下
                      10, // 左
                    ],
                    height: 50,
                    itemGap: 10,
                  }}
                  pieStyle={{
                    width: "100%",
                    height: "100%",
                    radius:
                      pieData.length > 15
                        ? [55, 80]
                        : pieData.length > 10
                        ? [50, 70]
                        : [40, 60],
                  }}
                  color={[...getBaseColors()]}
                />
              ) : (
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    height: "100%",
                    width: "100%",
                    justifyContent: "center",
                    paddingBottom: 10,
                  }}
                >
                  <EventEmpty title="暂无数据" />
                </div>
              )}
            </div>
          )}
          {curMenu === "3" && (
            <div className={styles.tableChartBox_chart}>
              <span>金额占比</span>
              {barData.xaxis?.length > 0 ? (
                <StackBarVer
                  idName="actualRep-bar"
                  data={barData.yaxis || []}
                  legend={barData.legend || []}
                  xAxis={barData.xaxis || []}
                  color={[...getBaseColors()]}
                />
              ) : (
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    height: "100%",
                    width: "100%",
                    justifyContent: "center",
                    paddingBottom: 10,
                  }}
                >
                  <EventEmpty title="暂无数据" />
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </Spin>
  );
};

export default TableChart;
